﻿using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.Remoting.Messaging;

namespace Jerkymon.Service
{
    //class EmailService
    //{
    //}

    /// <summary>
    /// USAGE:
    /// EmailUtil eu = new EmailUtil(); 
    /// eu.HtmlFilePath=@"c:\temp\file.htm";
    /// eu.Subject ="test message";
    /// eu.SmtpServer="mail.myserver.com";
    /// eu.FromEmail="you@yourserver.com";
    /// (loop here through your datatable etc. of email recipients ---)
    /// eu.SendEmailAsync("daddy longlegs", "dlonglegs@yahoo.com");
    /// eu.SendEmailAsync("Mama Bear", "mamabear@mindless.com");
    /// eu.SendEmailAsync("Bill Clinton", "billy@clinton.org");
    /// eu.SendEmailAsync("Jack Spratt", "sprattsksy@yayhey.com");
    /// Reference URL : http://www.eggheadcafe.com/articles/20030720.asp
    /// 
    /// DataTable dt = ds.Tables[0];
    /// EmailAsync eu = new EmailAsync();
    /// eu.HtmlFilePath=@"c:\temp\file.htm";
    /// eu.Subject ="Newsletter for you!";
    /// eu.SmtpServer="mail.myserver.com";
    /// eu.FromEmail="you@yourserver.com";
    /// for (int i =0; i<dt.Rows.count;i++)
    /// {
    ///     eu.SendEmailAsync(dt.Rows[0].Items["name"].ToString(), dt.Rows[0].Items["email"].ToString());
    /// }
    /// </summary>
    /// 
    public class EmailService
    {
		#region Delegates (1)
		public delegate string SendEmailDelegate(string name, string emailAddress);
		#endregion

		#region Static Methods (3)
		/// <summary>
        /// HOW TO send an email programmatically using C# with GMail
        /// Url : http://mvark.blogspot.com/2006/09/sending-mail-programmatically-using-c.html
        /// System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
        /// System.Net.NetworkCredential cred = new System.Net.NetworkCredential("yourid@gmail.com", "yourpwd");
        /// mail.To.Add("acme@acme.com");
        /// mail.Subject = "subject";
        /// mail.From = new System.Net.Mail.MailAddress("yourid@gmail.com");
        /// mail.IsBodyHtml = true;
        /// mail.Body = "message";
        /// System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com");
        /// smtp.UseDefaultCredentials = false;
        /// smtp.EnableSsl = true;
        /// smtp.Credentials = cred;
        /// smtp.Port = 587;
        /// smtp.Send(mail);
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="isSMTP"></param>
        /// <param name="isEmailUserName"></param>
        /// <param name="isEmailPassword"></param>
        /// <returns></returns>
        public static bool SendMail(System.Net.Mail.MailMessage msg, string isSMTP, int isSMTPPort, string isEmailUserName, string isEmailPassword)
        {
            return SendMail(msg, isSMTP, isSMTPPort, isEmailUserName, isEmailPassword, false);
        }

		public static bool SendMail(System.Net.Mail.MailMessage msg, string isSMTP, int isSMTPPort, string isEmailUserName, string isEmailPassword, bool ssl)
        {
            string err = string.Empty;
            return SendMail(msg, isSMTP, isSMTPPort, isEmailUserName, isEmailPassword, ssl, ref err);
        }

		public static bool SendMail(System.Net.Mail.MailMessage msg, string isSMTP, int isSMTPPort, string isEmailUserName, string isEmailPassword, bool ssl, ref string error)
        {

            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(isSMTP);
            
            if ((string.IsNullOrEmpty(isEmailUserName)) || (string.IsNullOrEmpty(isEmailPassword)))
            {
                //smtp.UseDefaultCredentials = true;
                smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            }
            else
            {
                System.Net.NetworkCredential cred = new System.Net.NetworkCredential(isEmailUserName, isEmailPassword);
                smtp.UseDefaultCredentials = false;
                smtp.Credentials = cred;
            }

            smtp.EnableSsl = ssl;
            

            if (isSMTPPort == 0)
                isSMTPPort = 25;

            smtp.Port = isSMTPPort;

            try
            {
                smtp.Send(msg);
                return true;
            }
            catch (Exception ex)
            {
                error += ex.ToString() + "<br>";
                return false;
            }

        }
		#endregion

		#region Fields (11)
		public bool isHTML = true;
		bool smtpSSL;

		int smtpPort;

		private string fromEmail;
		private string fromEmailSender;
		private string htmlFilePath;
		string smtpPassword;
		private string smtpServer;
		string smtpUsername;
		public string strBody = String.Empty;
		private string subject;
		#endregion

		#region Properties (9)
		public string FromEmail
        {
            get
            {
                return fromEmail;
            }

            set
            {
                fromEmail = value;
            }
        }
		public string FromEmailSender
        {
            get
            {
                return fromEmailSender;
            }

            set
            {
                fromEmailSender = value;
            }
        }
		public string HtmlFilePath
        {
            get
            {
                return htmlFilePath;
            }
            set
            {
                htmlFilePath = value;
            }
        }
		public string SmtpPassword
        {
            get
            {
                return smtpPassword;
            }

            set
            {
                smtpPassword = value;
            }
        }
		public int SmtpPort
        {
            get
            {
                return smtpPort;
            }
            set
            {
                smtpPort = value;
            }
        }
		public bool SmtpSSL
        {
            get
            {
                return smtpSSL;
            }

            set
            {
                smtpSSL = value;
            }
        }
		public string SmtpServer
        {
            get
            {
                return smtpServer;
            }
            set
            {
                smtpServer = value;
            }
        }
		public string SmtpUsername
        {
            get
            {
                return smtpUsername;
            }

            set
            {
                smtpUsername = value;
            }
        }
		public string Subject
        {
            get
            {
                return subject;
            }
            set
            {
                subject = value;
            }
        }
		#endregion

		#region Methods (3)

		public void GetResultsOnCallback(IAsyncResult ar)
        {
            SendEmailDelegate del = (SendEmailDelegate)
             ((AsyncResult)ar).AsyncDelegate;
            try
            {
                string result;
                result = del.EndInvoke(ar);
                Debug.WriteLine("\nOn CallBack: result is " + result);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\nOn CallBack, problem occurred: " + ex.Message);
            }
        }

		public string SendEmail(string name, string emailAddress)
        {
            if (strBody == String.Empty)
            {
                try
                {
                    using (StreamReader reader = new StreamReader(this.HtmlFilePath))
                    {
                        strBody = reader.ReadToEnd();
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("error reading HTML File" + ex.Message);
                }
            }
            try
            {
                bool isresult;
                System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
                //Message.IsBodyHtml = MailFormat.Html;
                Message.IsBodyHtml = this.isHTML;

                //Message.To = emailAddress;

                if (!string.IsNullOrEmpty(name))
                    //Message.To = name + " <" + emailAddress + ">";
                    Message.To.Add(new System.Net.Mail.MailAddress(emailAddress, name));
                else
                    //Message.To = emailAddress;
                    Message.To.Add(emailAddress);

                if (!string.IsNullOrEmpty(this.FromEmailSender))
                    //Message.From = this.FromEmailSender + " <" + this.FromEmail + ">";
                    Message.From = new System.Net.Mail.MailAddress(this.FromEmail, this.FromEmailSender);
                else
                    //Message.From = this.FromEmail;
                    Message.From = new System.Net.Mail.MailAddress(this.FromEmail);

                Message.Subject = this.Subject;
                Message.Body = strBody;
                //SmtpMail.SmtpServer = this.SmtpServer;
                //SmtpMail.Send(Message);
                isresult = SendMail(Message, this.SmtpServer, this.SmtpPort, this.smtpUsername, this.SmtpPassword, this.SmtpSSL);

                if (isresult)
                    return "sent" + name;
                else
                    return "Send error to " + emailAddress;
                //try
                //{
                //    MailMessage Message = new MailMessage();
                //    Message.BodyFormat = MailFormat.Html;
                //    Message.To = emailAddress;
                //    Message.From = this.FromEmail;
                //    Message.Subject = this.Subject;
                //    Message.Body = strBody;
                //    SmtpMail.SmtpServer = this.SmtpServer;
                //    SmtpMail.Send(Message);
                //}
                //catch (System.Web.HttpException ehttp)
                //{
                //    throw new Exception("Send error" + ehttp.Message);
                //}
                //return "sent" + name;


            }
            catch (System.Web.HttpException ehttp)
            {
                //throw new Exception("Send error" + ehttp.Message);

                return "sent" + ehttp.Message;

            }


        }

		public string SendEmailAsync(string name, string emailAddress)
        {
            SendEmailDelegate dc = new SendEmailDelegate(this.SendEmail);
            AsyncCallback cb = new AsyncCallback(this.GetResultsOnCallback);
            IAsyncResult ar = dc.BeginInvoke(name, emailAddress, cb, null);
            return "ok";
        }

		#endregion
    } // end class EmailUtil 
}
